function expandNodes(nodes, expandflag) {
    if (!nodes) return;
    let expandnode;
    for (let i = 0, l = nodes.length; i < l; i++) {
        if (expandflag == 'init') {
            expandnode = nodes[i];
        } else {
            expandnode = zTreeObj.getNodeByParam('id', nodes[i])
        }
        all_node = all_node.concat(expandnode.id);
        if (expandnode.isParent && !expandnode.zAsync) {
            zTreeObj.expandNode(expandnode, true, false, false);
        }
    }
}

function getallnodes(nodes, flag) {
    let data = [];
    for (let i = 0, l = nodes.length; i < l; i++) {
        if (nodes[i].children) {
            data = data.concat(getallnodes(nodes[i].children));
        }
        if (all_node.indexOf(nodes[i].id) == -1) {
            data = data.concat(nodes[i]);
        }
    }
    return data;
}

function onAsyncSuccess() {
    nodes = getallnodes(zTreeObj.getNodes());
    expandNodes(nodes, 'init');
}

function show_permissions(permissions) {
    zTreeObj.checkAllNodes(false);
    let node;
    $.each(permissions, function (i, item) {
        node = zTreeObj.getNodeByParam("id", item, null);
        if (!node.isParent){
            zTreeObj.checkNode(node, true, true);
        }
    });
}

function getpermissionsinfo(role_list, flag = 'user', func = null) {
    // 获取角色的全新信息
    $.when($.ajax({
        data: {'rl': role_list, 'type': 'r2p',},
        type: 'GET',
        url: distribute_url,
        traditional: true,
        success: function (data) {
            if (data['status'] == 0) {
                // 正常返回
                $('#permission_warining_message').text(data['msg']).parent().addClass('d-none');
                if (flag == 'user') {
                    user_permissions = data['permissions'];
                } else if (flag == 'role') {
                    role_permissions = data['permissions'];
                }
            } else {
                // 请求出错
                $('#permission_warining_message').text(data['msg']).parent().removeClass('d-none');
                if (flag == 'user') {
                    user_permissions = [];
                } else if (flag == 'role') {
                    role_permissions = [];
                }
            }
            if (flag == 'user') {
                show_permissions(user_permissions);
            } else if (flag == 'role') {
                show_permissions(role_permissions);
            }
        }
    })).done(func);
}

function showuserinfo(uid, roles) {
    let role_list = [];
    $('.category-list a').css({'text-decoration': 'none',});
    $('.category-list a[uid=' + uid + ']').css({'text-decoration': 'underline',});
    $('#role_dropdown_menu').removeClass('d-none');
    $('#user_warining_message').text('').addClass('d-none');
    $('#role_table input').iCheck('uncheck');
    $.each(roles, function (i, item) {
        $("#role_checkbox_" + i).iCheck('check');
        role_list.push(i);
    });
    return role_list
}

function getuserinfo() {
    // 获取所有用户角色信息
    $.ajax({
        data: {'uid': uid, 'type': 'u2r',},
        type: 'GET',
        url: distribute_url,
        success: function (data) {
            if (data['status'] == 0) {
                // 正常返回
                refresh[1] = data['uid'];
                refresh[2] = data['role'];
                refresh[3] = showuserinfo(refresh[1], refresh[2]);
                getpermissionsinfo(refresh[3]);
            } else if (data['status'] == 201) {
                // 默认的uid
                $('.category-list a').css({'text-decoration': 'none',});
                $('.category-list a[uid=' + data['uid'] + ']').css({'text-decoration': 'underline',});
                $('#role_dropdown_menu').removeClass('d-none');
                $('#user_warining_message').text(data['msg']).removeClass('d-none');
            } else if (data['status'] == 202) {
                // 无效的uid
                $('.category-list a').css({'text-decoration': 'none',});
                $('#role_dropdown_menu').add('d-none');
                $('#user_warining_message').text(data['msg']).removeClass('d-none');
            } else if (data['status'] == 203) {
                // uid 不存在
                $('.category-list a').css({'text-decoration': 'none',});
                $('#role_dropdown_menu').add('d-none');
                $('#user_warining_message').text(data['msg']).removeClass('d-none');
            }
        }
    })
}

function change_role_refresh_flag() {
    if (role_permissions) {
        $('.r2psetting i').removeClass('fa-refresh').removeClass('fa-spin').addClass('fa-paint-brush');
        $('#role_' + refresh[4] + ' .r2psetting').children('i').addClass('fa-refresh').addClass('fa-spin').removeClass('fa-paint-brush');
        $('#permissions_dropdown_menu').removeClass('d-none');
    }
}

let all_node = [];
let user_permissions;
let role_permissions;
let zTreeObj;
let setting = {
    check: {
        enable: true
    },
    view: {
        fontCss: {'color': 'black', 'font-weight': 'bold'},//字体样式函数
        showLine: false,
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    async: {
        enable: true,
        url: distribute_url,
        autoParam: ["id=node_id",],
        otherParam: {"type": "menu"},
        type: "get",
    },
    callback: {
        onAsyncSuccess: onAsyncSuccess,
    },
};
// 单个角色的权限是否有更新, 当前uid, 当前用户角色, 当前用户角色id, 当前编辑角色id
let refresh = [0, 0, [], [], 0];

$(document).ready(function () {
    // checkbox样式
    $('#role_table input').iCheck({
        checkboxClass: 'icheckbox_square-blue',
        radioClass: 'iradio_square-blue',
    });
    // 初始化权限树
    zTreeObj = $.fn.zTree.init($("#PermissionTree"), setting,);
    // 初始化toastr
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "progressBar": true,
        "preventDuplicates": false,
        "positionClass": "toast-top-right",
        "onclick": null,
        "showDuration": "400",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
    // 初始化信息
    if (init) {
        getuserinfo();
    }
    // 点击用户
    $('.category-list a').click(function () {
        $('.r2psetting i').removeClass('fa-refresh').removeClass('fa-spin').addClass('fa-paint-brush');
        if (uid == $(this).attr('uid')) {
            showuserinfo(refresh[1], refresh[2]);
            show_permissions(user_permissions);
        } else {
            // TODO： 缓存每一次的请求信息
            uid = $(this).attr('uid');
            getuserinfo();
        }
        $('#permissions_dropdown_menu').addClass('d-none');
        return false;
    });
    // 点击角色
    $('.r2psetting').click(function () {
        if ($(this).children('i').hasClass('fa-spin')) {
            $('.r2psetting i').removeClass('fa-refresh').removeClass('fa-spin').addClass('fa-paint-brush');
            $('#permissions_dropdown_menu').addClass('d-none');
            if (refresh[0] == 1) {
                getuserinfo();
            } else if (refresh[0] == 0) {
                show_permissions(user_permissions);
            }
        } else {
            // TODO: 缓存每一个role_id信息，节省带宽
            if (refresh[4] == $(this).parent().parent().attr('id').split('_')[1]) {
                show_permissions(role_permissions);
                change_role_refresh_flag();
            } else {
                refresh[4] = $(this).parent().parent().attr('id').split('_')[1];
                getpermissionsinfo([refresh[4],], 'role', change_role_refresh_flag)
            }
        }
    });
    // 提交用户角色信息
    $('#save_user_roles').click(function () {
        let rl = [];
        $('input:checkbox:checked').each(function (index, item) {
            rl.push($(this).val());
        });
        $.ajax({
            data: {'uid': uid, 'rl': rl, 'type': 'u2r', 'csrfmiddlewaretoken': token},
            type: 'POST',
            url: distribute_url,
            traditional: true,
            success: function (data) {
                if (data['status'] != 0) {
                    toastr["error"]("保存出错", data['msg'])
                } else {
                    toastr["success"]("保存成功", data['msg']);
                    getuserinfo();
                }
            },
        })
    })
    // 提交角色权限信息
    $('#save_role_permissions').click(function () {
        let pl = [];
        nodes = zTreeObj.getCheckedNodes(true);
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].permission && pl.indexOf(nodes[i].permission) == -1) {
                pl.push(nodes[i].permission);
            }
        }
        $.ajax({
            data: {'rid': refresh[4], 'pl': pl, 'type': 'r2p', 'csrfmiddlewaretoken': token},
            type: 'POST',
            url: distribute_url,
            traditional: true,
            success: function (data) {
                if (data['status'] != 0) {
                    toastr["error"]("保存出错", data['msg'])
                } else {
                    toastr["success"]("保存成功", data['msg']);
                    refresh[0] = 1;
                }
            },
        })
    })
});
